package com.cl.code.database.mybatis.module.sql.table;

import lombok.Getter;

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author chengliang
 * @since 1.0.0
 */
@Getter
public class TableInfo {

    private final Class<?> entityClass;

    private final String tableName;

    private final TableField[] tableFields;

    private final IdField idField;

    private final LogicDeleteField logicDeleteField;

    private final VersionField versionField;

    public TableInfo(Class<?> entityClass, String tableName, TableField[] tableFields) {
        this.entityClass = entityClass;
        this.tableName = tableName;
        this.tableFields = tableFields;

        Function<Class<?>, List<TableField>> filter = clazz -> Arrays.stream(tableFields).filter(tableField -> clazz.isAssignableFrom(tableField.getClass())).collect(Collectors.toList());

        List<TableField> list = filter.apply(IdField.class);
        if (list.isEmpty()) {
            throw new IllegalArgumentException(tableName + " table need a primary key");
        } else if (list.size() > 1) {
            throw new IllegalArgumentException(tableName + " table can only have one primary key");
        } else {
            idField = (IdField) list.get(0);
        }

        List<TableField> list1 = filter.apply(LogicDeleteField.class);
        if (list1.size() > 1) {
            throw new IllegalArgumentException(tableName + " table can only have one logic delete field");
        } else {
            logicDeleteField = list1.isEmpty() ? null : (LogicDeleteField) list1.get(0);
        }

        List<TableField> list2 = filter.apply(VersionField.class);
        if (list2.size() > 1) {
            throw new IllegalArgumentException(tableName + " table can only have one version field");
        } else {
            versionField = list2.isEmpty() ? null : (VersionField) list2.get(0);
        }
    }

    public boolean isSupportLogicDelete() {
        return logicDeleteField != null;
    }

    public boolean isSupportVersion() {
        return versionField != null;
    }

}
